package com.smart.wap.service;


import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.service.WxPayService;
import com.smart.common.exception.SmartException;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 微信支付处理程序
 *
 * @author xiaxuqiu
 * @date 2022/10/27
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class WXPayHandler {

    private final WxPayService wxPayService;


    /**
     * 推送APP发起的订单到微信服务器
     *
     * @param orderId   系统订单号
     * @param fee       订单支付金额
     * @param notifyUrl 订单回调地址
     * @param attach    订单附加地址
     * @return {@code Object}
     */
    public Object pushCoinOrderToWechat(String appId, String orderId, BigDecimal fee, String notifyUrl, String attach) {
        try {
            WxPayService currentService = wxPayService.switchoverTo(appId);
            int payAmount = fee.multiply(BigDecimal.valueOf(100L)).intValue();
            WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount().setCurrency("CNY").setTotal(payAmount);
            WxPayUnifiedOrderV3Request v3Request = new WxPayUnifiedOrderV3Request();
            v3Request.setOutTradeNo(orderId).setAmount(amount).setAttach(attach).setDescription("系统服务费").setNotifyUrl(notifyUrl);
            return currentService.createOrderV3(TradeTypeEnum.APP, v3Request);
        } catch (Exception e) {
            throw new SmartException("微信支付创建失败:" + e.getMessage());
        }
    }


    public Object pushJsApiWechat(String appId, String orderId, BigDecimal fee, String notifyUrl, String attach,String openId) {
        try {
            WxPayService currentService = wxPayService.switchoverTo(appId);
            int payAmount = fee.multiply(BigDecimal.valueOf(100L)).intValue();
            WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount().setCurrency("CNY").setTotal(payAmount);
            WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer().setOpenid(openId);
            WxPayUnifiedOrderV3Request v3Request = new WxPayUnifiedOrderV3Request();
            v3Request.setPayer(payer).setAppid(appId).setOutTradeNo(orderId).setAmount(amount).setAttach(attach).setDescription("系统服务费").setNotifyUrl(notifyUrl);
            return currentService.createOrderV3(TradeTypeEnum.JSAPI, v3Request);
        } catch (Exception e) {
            throw new SmartException("微信支付创建失败:" + e.getMessage());
        }
    }


}
